package com.ufox.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ufox.entity.Cartitem;
import com.ufox.entity.Products;
import com.ufox.entity.Result;
import com.ufox.service.ICartitemService;
import com.ufox.service.IProductsService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 优狐科技-www.hbufox.com
 * @since 2022-06-09
 */
@RestController
@RequestMapping("/cartitem")
public class CartitemController {

    @Autowired
    private ICartitemService cartitemService;

    @Autowired
    private IProductsService productsService;

    //将商品加入购物车 AddToCart

    @GetMapping("/AddToCart/{userId}/{prodId}")
    public Result AddToCart(@PathVariable String userId,@PathVariable String prodId) {
        return cartitemService.addCart(userId+"",prodId+"");
    }

    @GetMapping("/clearCart/{userId}")
    public Result clearCart(@PathVariable String userId) {
        return cartitemService.clearCart(userId);
    }

    @GetMapping("/findCartByUserId/{userId}")
    public Result findCartByUserId(@PathVariable String userId) {
        return cartitemService.findCartByUserId(userId);
    }

    @GetMapping("/getCount/{userId}")
    public Result getCountByUserId(@PathVariable String userId) {
        return cartitemService.getCountByUserId(userId);
    }

    @GetMapping("/getSum/{userId}")
    public Result getSum(@PathVariable String userId) {
        Map<Products,Integer> map = cartitemService.findSum(userId);

        Set<Map.Entry<Products, Integer>> entries = map.entrySet();

        double sum = 0;
        for(Map.Entry<Products, Integer> entry:entries){
            Products products = entry.getKey();
            Integer num = entry.getValue();

            sum += products.getPrice()*num;
        }

        return Result.ok("",sum);
    }

    @DeleteMapping("/delCartById/{userId}/{prodId}/{pnum}")
    public Result delCartById(@PathVariable String userId,@PathVariable String prodId,@PathVariable String pnum) {
        return cartitemService.delCartById(userId,prodId,pnum);
    }

    @DeleteMapping("/delCartByIdAndInsert/{userId}/{prodId}/{pnum}")
    public Result delCartByIdAndInsert(@PathVariable String userId,@PathVariable String prodId,@PathVariable String pnum) {
        return cartitemService.delCartByIdAndInsert(userId,prodId,pnum);
    }



}

